var baseDate = null;
var startDate = null;

var count = 0;
var updateBaseDateInterval = null;

function getLocalDate(){
    if(!baseDate && count <= 3){
        let timestamp = getAccurateTimestamp();
        baseDate = new Date(timestamp);
        startDate = new Date();
        // console.error("开始网络对时：",baseDate.getTime());
        count++;
    }
    // console.log(baseDate.getTime());

    if(!updateBaseDateInterval && count <= 3){
        var delay = 10;
        updateBaseDateInterval = setInterval(() => {
            // // console.log("定时更新本地时间:",baseDate.getTime(),startDate.getTime(),baseDate.getTime(),Math.abs(startDate.getTime() - baseDate.getTime()))
            let nowTimestamp = new Date().getTime();
            let diff =  Math.abs(nowTimestamp - startDate.getTime());
            
            startDate = new Date(nowTimestamp);
            baseDate = new Date(baseDate.getTime() + diff);
            // console.log("定时更新本地时间:",baseDate.getTime(),diff)
        }, delay);
    }

    return baseDate;
}

function getAccurateTimestamp() {
    // 获取请求发送前的本地时间
    var startLocalTime = new Date().getTime();

    let timestamp = getTaobaoTimestamp()

    // 获取请求结束后的本地时间
    var endLocalTime = new Date().getTime();

    // 计算网络延迟的中间时间点
    var networkDelay = parseInt((endLocalTime - startLocalTime) / 2);
    // var networkDelay = parseInt((endLocalTime - startLocalTime));
    // console.log("TTL: " + networkDelay);

    // 加上网络延迟的修正
    var adjustedTimestamp = timestamp + networkDelay;

    return adjustedTimestamp;
}

function getTime(){
    // 请求时间戳API
    var response = http.get("https://db.yearnstudio.cn/time");
    if (response.statusCode != 200) {
        throw new Error("请求失败，状态码: " + response.statusCode);
    }

    // 解析API返回的数据
    try {
        const timestamp = parseInt(response.body.string());
        return timestamp;
    } catch (e) {
        // console.error("获取时间戳失败,采用本地时间: " + e.message);
        return new Date().getTime();
    }
}
// http://time.syiban.com/t-taobao.php
// 淘宝时间戳API
function getTaobaoTimestamp() {
    var response = http.get("http://acs.m.taobao.com/gw/mtop.common.getTimestamp/");
    var data = response.body.json();
    return parseInt(data.data.t); // 返回时间戳
}











// 创建悬浮窗
let window = floaty.window(
    <vertical id="frame" bg="#000000" alpha="0.8" padding="8dp">
        <horizontal>
            <text textSize="16sp" textColor="#ffffff" text="北京时间:" />
            <text id="timeText" textSize="16sp" textColor="#ffffff"/>
        </horizontal>
        <horizontal>
            <text textSize="16sp" textColor="#ffffff" text="本机时间:" />
            <text id="timeText2" textSize="16sp" textColor="#ffffff" />
        </horizontal>
    </vertical>
);

// 设置悬浮窗初始位置靠屏幕右上角
// 获取屏幕宽度和高度
let screenWidth = device.width;
let screenHeight = device.height;
setTimeout(() => {
    window.setPosition(screenWidth - window.getWidth(), 0);
}, 100); // 延迟 100 毫秒

ui.run(() => {
    window.timeText.setText("网络校时中...");
});

// 每隔 1 毫秒更新时间
let interval = setInterval(() => {
    let currentTime = getLocalDate();
    let timeString = formatTime(currentTime);
    ui.run(() => {
        window.timeText.setText(timeString);
        window.timeText2.setText(formatTime(new Date()));
    });
}, 10);



// 使用主线程更新 UI


// 时间格式化函数
function formatTime(date) {
    let hours = padZero(date.getHours());
    let minutes = padZero(date.getMinutes());
    let seconds = padZero(date.getSeconds());
    let milliseconds = padMilliseconds(date.getMilliseconds());
    return `${hours}:${minutes}:${seconds}.${milliseconds}`;
}

// 两位补零函数
function padZero(num) {
    return num < 10 ? "0" + num : num;
}

// 三位补零函数
function padMilliseconds(ms) {
    if (ms < 10) return "00" + ms;
    if (ms < 100) return "0" + ms;
    return ms;
}